#include "EyerWASMBlob_ReadEvent.hpp"

#include <emscripten.h>

extern "C"
{
EMSCRIPTEN_KEEPALIVE int EyerWASMBlob_ReadEvent_Read(void * ctx, int blobKey, int pos, int wantLen);

EMSCRIPTEN_KEEPALIVE int EyerWASMBlob_ReadEvent_Read_OnSucc(void * ctx, uint8_t * buffer, size_t size)
{
    Eyer::EyerWASMBlob_ReadEvent * event = (Eyer::EyerWASMBlob_ReadEvent *)ctx;
    return event->EyerWASMBlob_ReadEvent_Read_OnSucc(buffer, size);
}

EMSCRIPTEN_KEEPALIVE int EyerWASMBlob_ReadEvent_Read_OnFail(void * ctx)
{
    Eyer::EyerWASMBlob_ReadEvent * event = (Eyer::EyerWASMBlob_ReadEvent *)ctx;
    return event->EyerWASMBlob_ReadEvent_Read_OnFail();
}
}

namespace Eyer
{
    EyerWASMBlob_ReadEvent::EyerWASMBlob_ReadEvent(int blobKey, int64_t pos, int64_t wantLen)
    {
        m_blobKey = blobKey;
        m_pos = pos;
        m_wantLen = wantLen;
    }

    EyerWASMBlob_ReadEvent::~EyerWASMBlob_ReadEvent()
    {

    }

    int EyerWASMBlob_ReadEvent::Run()
    {
        EyerWASMBlob_ReadEvent_Read(this, m_blobKey, m_pos, m_wantLen);
        return 0;
    }

    int EyerWASMBlob_ReadEvent::EyerWASMBlob_ReadEvent_Read_OnSucc(uint8_t * buffer, size_t size)
    {
        std::unique_lock<std::mutex> lck(mtx);
        isFinished = true;
        isSucced = true;
        m_buffer.SetBuffer(buffer, size);
        cond.notify_all();
        return 0;
    }

    int EyerWASMBlob_ReadEvent::EyerWASMBlob_ReadEvent_Read_OnFail()
    {
        std::unique_lock<std::mutex> lck(mtx);
        isFinished = true;
        isSucced = false;
        cond.notify_all();
        return 0;
    }

    EyerWASMBuffer EyerWASMBlob_ReadEvent::GetBuffer()
    {
        return m_buffer;
    }
}